package materials

import (
	"context"
	"net/http"
	"wms/model"

	"wms/internal/svc"
	"wms/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type MaterialsUpdateLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewMaterialsUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MaterialsUpdateLogic {
	return &MaterialsUpdateLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *MaterialsUpdateLogic) MaterialsUpdate(req *types.MaterialsUpdateRequest) (resp *types.BaseResponse, err error) {
	resp = new(types.BaseResponse)
	//1.原料规格是否存在
	_, err = l.svcCtx.MaterialsModel.FindOne(l.ctx, req.Id)
	switch err {
	case nil:
	//不处理
	case model.ErrNotFound: //不存在
		resp.Code = http.StatusBadRequest
		resp.Msg = "原料规格不存在"
		return resp, nil
	default: //其他错误
		resp.Code = http.StatusInternalServerError
		resp.Msg = "服务内部错误"
		return resp, nil
	}

	//2.原料规格信息入库
	err = l.svcCtx.MaterialsModel.Update(l.ctx, &model.Materials{
		Id:    req.Id,
		Name:  req.Name,
		Types: req.Types,
	})

	if err != nil {
		if err == model.ErrNotFound {
			resp.Code = http.StatusNoContent
			resp.Msg = "原料规格不存在"
			return resp, nil
		}

		resp.Code = http.StatusInternalServerError
		resp.Msg = "服务内部错误"
		return resp, nil
	}

	resp.Code = http.StatusOK
	resp.Msg = "成功"
	return resp, nil
}
